package com.bosi.exmple.chat;

import com.alibaba.fastjson.JSON;
import com.bosi.exmple.chat.entity.WSRequest;
import com.bosi.exmple.chat.entity.WSResponse;
import com.bosi.exmple.ws.server.WebSocketSession;
import com.bosi.exmple.ws.server.WebSocketServer;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatWebSocket extends MessageCenter implements WebSocketServer {

    @Override
    public void onOpen(WebSocketSession session) {
        WSRequest req = new WSRequest();
        req.setSession(session);
        get("open").apply(req);
    }

    @Override
    public void onMessage(WebSocketSession session, String message) {
        log.debug("服务端收到客户端[{}]的消息:{}", session.getId(), message);

        WSRequest req = JSON.parseObject(message, WSRequest.class);
        req.setSession(session);

        Object handResult = get(req.getAct()).apply(req);
        if(req.getId() != 0 || handResult != null){
            WSResponse res = new WSResponse();
            res.setId(req.getId());
            res.setAct(req.getAct());
            res.setCode(200);
            res.setData(handResult);

            sendMessage(res,session);
        }
    }

    @Override
    public void onError(WebSocketSession session, Throwable e) {
        log.warn(e.getMessage(),e);

        WSResponse res = new WSResponse();
        res.setAct("error");
        res.setCode(500);
        res.setData(e.getMessage());

        sendMessage(JSON.toJSONString(res),session);
    }

    @Override
    public void onClose(WebSocketSession session) {
        WSRequest req = new WSRequest();
        req.setSession(session);
        get("close").apply(req);
    }

    /**
     * 服务端发送消息给客户端
     */
    public static void sendMessage(Object message, WebSocketSession session) {
        if(message == null || session == null) return;

        try {
            String msg;
            if(message instanceof String){
                msg = message.toString();
            }else {
                msg = JSON.toJSONString(message);
            }

            session.getChannel().writeAndFlush(new TextWebSocketFrame(msg));
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }
}
